package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.dubbo.api.CommentsApi;
import com.itheima.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongoDb.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserThreadLocal;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Pan Rundong
 * @Date 2023-03-02 21:07
 * @Desc 评论Service
 */
@Service
public class CommentsService {
    @DubboReference
    private CommentsApi commentsApi;
    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    /**
     * 动态查询评论
     *
     * @param page
     * @param pagesize
     * @param movementId
     * @return com.tanhua.model.vo.PageResult
     * @Author Pan Rundong
     */
    public PageResult getComments(Integer page, Integer pagesize, String movementId) {
        //1.调用Api查询所有评论
        List<Comment> list = commentsApi.fingById(movementId, CommentType.COMMENT, page, pagesize);

        if (list == null || list.size() == 0) {
            return new PageResult();
        }

        //2.获取所有用户Id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);

        //3.调用Api获取用户信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);

        //4.封装Vo
        List<CommentVo> voList = list.stream().map((comment) -> {
            //4.1 创建对象
            CommentVo vo = CommentVo.init(userInfoMap.get(comment.getUserId()), comment);
            //4.2 返回
            return vo;
        }).collect(Collectors.toList());

        //5.返回
        return new PageResult(page, pagesize, voList.size(), voList);
    }

    /**
     * 发布评论
     *
     * @param map
     * @return void
     * @Author Pan Rundong
     */
    public void publish(Map map) {
        //1.获取各参数
        String movementId = (String) map.get("movementId");
        String commentTxt = (String) map.get("comment");
        Long userId = UserThreadLocal.getUserId();
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setPublishId(new ObjectId(movementId));
        comment.setContent(commentTxt);
        comment.setCreated(System.currentTimeMillis());

        //2.调用Api发布评论
        int count = commentsApi.publish(comment);
    }
}
